<script setup lang="ts">
import arrowDown from '/images/webp/affiliate-program/arrow-down.webp'
import AppDatePicker from '~/components/AppDatePicker.vue'
import BaseImage from '~/components/BaseImage.vue'
import dayjs from 'dayjs'
import AppSelect from '~/components/AppSelect.vue'

// 添加useI18n
const { t } = useI18n()

interface DateOptionItem {
  label: string
  value: string[]
}
const date = ref([])
const { bonus_currency } = storeToRefs(useAffiliate())
const { isLogin } = storeToRefs(useAppStore())
const selectedPeriod = ref(t('affiliate_program_today'))
const dateRange = ref('2024-12-18 到 2024-12-25')
const selectedType = ref('')
const currentLabel = ref(t('affiliate_program_all_types'))
const lock = ref(false)
const dateSelect = ref()

const showTypeSelect = ref(false)

interface OptionItem {
  label: string
  value: number
}
definePageMeta({
  layout: 'header-back',
  title:'affiliate_program_commission_record'
});

const {
  list,
  page,
  page_size,
  loading,
  total,
  runAsync,
  resetPage,
} = useList(ApiAgencyCommissionRecordsNew, {}, { page_size: 5, isWatchPageOrPageSize: false })


// 时间周期选项
const periodOptions = ref<DateOptionItem[]>([
  { label: t('affiliate_program_today'), value: calculateDateRange('今天') },
  { label: t('affiliate_program_yesterday'), value: calculateDateRange('昨天') },
  { label: t('affiliate_program_this_week'), value: calculateDateRange('本周') },
  { label: t('affiliate_program_last_week'), value: calculateDateRange('上周') },
  { label: t('affiliate_program_this_month'), value: calculateDateRange('本月') },
  { label: t('affiliate_program_last_month'), value: calculateDateRange('上月') },
])

const getOptions = computed(() => {
  return [{
    label: t('affiliate_program_all_types'),
    value: '',
  }].concat(list.value?.map((item) => {
    return {
      label: item.cash_type_name,
      value: item.cash_type,
    }
  }) ?? [])
})


// 选择类型
function selectType(option: OptionItem): void {
  selectedType.value = option.value
  currentLabel.value = option.label
  showTypeSelect.value = false
}

function calculateDateRange(type: string) {
  const now = dayjs();
  let start, end;

  switch (type) {
    case '今天':
      start = now.startOf('day');
      end = now.endOf('day');
      break;

    case '昨天':
      start = now.subtract(1, 'day').startOf('day');
      end = now.subtract(1, 'day').endOf('day');
      break;

    case '本周':
      // ISO周：周一作为一周的开始
      start = now.startOf('week');
      end = now.endOf('week');
      break;

    case '上周':
      start = now.subtract(1, 'week').startOf('week');
      end = now.subtract(1, 'week').endOf('week');
      break;

    case '本月':
      start = now.startOf('month');
      end = now.endOf('month');
      break;

    case '上月':
      start = now.subtract(1, 'month').startOf('month');
      end = now.subtract(1, 'month').endOf('month');
      break;

    default:
      throw new Error('无效的类型: 请使用今天、昨天、本周、上周、本月、上月');
  }

  // 统一格式化为 yyyy-MM-dd HH:mm:ss
  return [start.format('YYYY-MM-DD HH:mm:ss'), end.format('YYYY-MM-DD HH:mm:ss')];
}


const showList = computed(()=>{
  return list.value?.slice(page_size.value*(page.value-1),page_size.value*page.value)
})

function formatTimestamp12H(timestamp: number) {
  return dayjs(timestamp).format('MM/DD hh:mm:ss');
}

// 切换页码
function changePage(direction: 'prev' | 'next') {
  if (direction === 'prev' && page.value > 1) {
    page.value--
  }
  else if (direction === 'next' && page.value < total.value) {
    page.value++
  }
}

const params = computed(() => {
  return {
    cash_type: selectedType.value,
    start_time: date.value[0],
    end_time: date.value[1],
    page_size: page_size.value,
    page: page.value,
  }
})

onMounted(() => {
  dateSelect.value && dateSelect.value.selectOption(periodOptions.value[0])
  watch(() => isLogin.value, (newValue) => {
    newValue && useListSearch(params, runAsync, resetPage)
  }, { immediate: true })
})
</script>

<template>
  <div class="commission-record-container"  :key="bonus_currency">
    <!-- 筛选器部分 -->
    <div class="filter-section">
      <!-- 日期筛选器 -->
      <div class="date-filters">
        <AppSelect ref="dateSelect" v-model="date" :options="periodOptions" />
        <AppDatePicker v-model="date" v-model:date-range-value="dateRange" />
      </div>

      <!-- 类型筛选器 -->
      <div class="type-filter">
        <div class="type-select" @click="showTypeSelect = true">
          <span>{{ currentLabel }}</span>
          <div class="arrow-icon">
            <BaseImage width="12px" :url="arrowDown" />
          </div>
        </div>
      </div>
    </div>

    <!-- 类型选择器弹出层 -->
    <div v-if="showTypeSelect" class="select-popup-container">
      <div class="popup-mask" @click.stop="showTypeSelect = false" />
      <div class="select-popup type-popup animated">
        <div class="popup-content">
          <div class="close-area">
            <div class="close-btn" @click="showTypeSelect = false">
              <span class="close-icon">×</span>
            </div>
          </div>
          <div class="popup-inner">
            <div v-for="option in getOptions" :key="option.value" class="select-option"
              :class="{ active: option.value === selectedType }" @click="selectType(option)">
              {{ option.label }}
              <div class="circle-container">
                <div v-if="option.value === selectedType" class="select-indicator" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 记录列表 -->
    <div class="record-list">
      <div v-for="(record, index) in showList" :key="index" class="record-item">
        <div class="record-row">
          <div class="record-label">
            {{ t('affiliate_program_type') }}
          </div>
          <div class="record-value"
            :class="{ 'type-commission': record.type === t('affiliate_program_commission_transfer'), 'type-agent': record.type === t('affiliate_program_agent_commission') }">
            {{ record.cash_type_name }}
          </div>
        </div>
        <div class="record-row">
          <div class="record-label">
            {{ t('affiliate_program_time') }}
          </div>
          <div class="record-value time-value">
            {{ formatTimestamp12H(record.apply_at) }}
          </div>
        </div>
        <div class="record-row">
          <div class="record-label">
            {{ t('affiliate_program_amount') }}
          </div>
          <div class="record-value amount-value">
            <BaseCurrencyIcon :cur="getCurrencyConfigByCode(bonus_currency)?.name"  />
            <span>{{ record.amount.toLocaleString() }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控制 -->
    <div class="pagination">
      <button class="page-button prev" :disabled="page === 1" @click="changePage('prev')">
        &lt;
      </button>
      <div class="page-info">
        <span class="current-page">{{ page.toString().padStart(2, '0') }}</span>
        <span class="page-divider">{{ t('affiliate_program_page_of') }}</span>
        <span class="total-pages">{{ total }}</span>
      </div>
      <button class="page-button next" :disabled="page === total" @click="changePage('next')">
        &gt;
      </button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.commission-record-container {
  background-color: #1a1d1e;
  color: white;
  min-height: 100vh;
  padding-bottom: 20px;
  overflow-y: scroll;
}

.filter-section {
  padding: 16px;

  .date-filters {
    display: flex;
    gap: 12px;
    margin-bottom: 12px;
  }

  .date-select {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #232626;
    border-radius: 8px;
    padding: 10px 15px;
    width: 100px;
    font-size: 14px;

    .icon-arrow-down {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-style: solid;
      border-width: 0 2px 2px 0;
      padding: 2px;
      transform: rotate(45deg);
    }
  }

  .date-range {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #232626;
    border-radius: 8px;
    padding: 10px 15px;
    font-size: 14px;
  }

  .type-filter {
    .type-select {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #232626;
      border-radius: 8px;
      padding: 10px 15px;
      font-size: 14px;
    }
  }
}

.record-list {
  margin: 0 16px;

  .record-item {
    background-color: #292d2e;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 8px;
    border: 1px solid var(---border-black-23A4142, #3a4142);

    .record-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4px 0;

      .record-label {
        font-size: 10px;
        color: #b3bec1;
      }

      .record-value {
        font-size: 10px;

        &.type-commission {
          color: #ffe175;
        }

        &.type-agent {
          color: #5ac8fa;
        }

        &.time-value {
          color: #B3BEC1;
        }

        &.amount-value {
          display: flex;
          font-size: 12px;
          align-items: center;
          color: #24ee89;

          span {
            margin-left: 4px;
            font-weight: 500;
          }
        }
      }
    }
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;

  .page-button {
    width: 32px;
    height: 38px;
    border-radius: 4px;
    background-color: #292d2e;
    border: none;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    cursor: pointer;

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }

  .page-info {
    display: flex;
    align-items: center;
    margin: 0 4px;
    background-color: #292d2e;
    border-radius: 4px;
    padding: 4px;
    font-size: 12px;

    .current-page {
      color: white;
      font-weight: 500;
      background: #3a4142;
      padding: 5px 12px;
      border-radius: 5.23px;

    }

    .page-divider {
      margin: 0 6px;
      color: #666;
    }

    .total-pages {
      color: white;
      padding: 5px 12px;
    }
  }
}

// 弹出选择器容器
.select-popup-container {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 100;

  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }
}

// 弹出选择器样式
.select-popup {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  z-index: 101;

  &.animated {
    animation: slideUp 0.3s ease-out forwards;
  }

  @keyframes slideUp {
    from {
      transform: translateY(100%);
    }

    to {
      transform: translateY(0);
    }
  }

  .popup-content {
    background-color: #1e2122;
    border-radius: 12px 12px 0 0;
    position: relative;

    .close-area {
      display: flex;
      justify-content: end;
      padding: 16px;
      position: relative;

      .close-btn {
        width: 28px;
        height: 28px;
        background: #4a5354;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;
        margin-bottom: 10px;

        .close-icon {
          font-size: 14px;
          font-weight: 700;
          color: #fff;
        }
      }
    }
  }

  .popup-inner {
    max-height: 40vh;
    overflow-y: scroll;
    padding: 0 0 20px;
  }

  .select-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 20px;
    font-size: 16px;
    position: relative;

    &.active {
      color: white;
      font-weight: 500;
      background-color: #323738;
    }

    .circle-container {
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        width: 20px;
        height: 20px;
        border: 1px solid #e4eaf030;
        border-radius: 50%;
      }
    }

    .select-indicator {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #24ee89;
      position: absolute;

      &::before {
        content: '';
        position: absolute;
        width: 10px;
        height: 10px;
        background: #323738;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        border-radius: 50%;
      }
    }
  }
}

.arrow-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #3a4142;
  border-radius: 4px;
}
</style>
